var exports = {};

var _zip = null;

var _issaveing = false;

function createThumbnail(callBack) {
	var tmpcanvas = document.createElement("canvas");
	var svg = document.getElementById("svgView");
	tmpcanvas.width = $(svg).width();
	tmpcanvas.height = $(svg).height();
	var currFace = Design.mainEditer.product.currFace;
	currFace.clip(true);
	if(currFace.bg && currFace.bg.repeat){
		currFace.showBgOnly(true);//隐藏除了重复背景的所有元素，以生成背景
		//图片方式生成背景
		createByImg(tmpcanvas, 1, function(){
			currFace.showBgOnly(false);
			currFace.showFgOnly(true);
			createByCanvg(tmpcanvas, 1, function(){
				var thumbnail = tmpcanvas.toDataURL();
				thumbnail = thumbnail.replace(/^data:image\/(png|jpg);base64,/, "");
				currFace.clip(false);
				callBack(thumbnail);
			});
		});
	}else{
		createByCanvg(tmpcanvas, 1, function(){
			var thumbnail = tmpcanvas.toDataURL();
			thumbnail = thumbnail.replace(/^data:image\/(png|jpg);base64,/, "");
			currFace.clip(false);
			callBack(thumbnail);
		});
	}
}

//canvg方式生成图片
//缺点：重复背景填充不支持
function createByCanvg(canvas, scale, callBack) {
	var svg = document.getElementById("svgView");
	var data = (new XMLSerializer()).serializeToString(svg);
	canvg(canvas, data, {
		scaleWidth: Design.stageW * scale,
		scaleHeight: Design.stageH * scale,
		ignoreClear: true,
		ignoreAnimation: true,
		ignoreMouse: true,
		ignoreDimensions: true,
		renderCallback: callBack
	});
}

//img的方式生成图片
//缺点：自定义字体不支持
function createByImg(canvas, scale, callBack) {
	var svg = document.getElementById("svgView");
	var ctx = canvas.getContext("2d");
	var data = (new XMLSerializer()).serializeToString(svg);
	var DOMURL = window.URL || window.webkitURL || window;
	var img = new Image();
	var svgBlob = new Blob([data], {
		type: "image/svg+xml;charset=utf-8"
	});
	var url = DOMURL.createObjectURL(svgBlob);
	img.onload = function() {
		var w = img.width * scale;
		var h = img.height * scale;
		ctx.drawImage(img, 0, 0, w, h);
		DOMURL.revokeObjectURL(url);
		callBack(canvas);
	};
	img.src = url;
}

function createProduction(callBack) {
	var currFace = Design.mainEditer.product.currFace;
	var realScale = currFace.realScale || 1;
	currFace.showFgOnly(false);
	
	var tmpcanvas = document.createElement("canvas");
	var ctx = tmpcanvas.getContext("2d");
	
	var bb = Design.mainEditer.stage.getBBox();
	var svg = document.getElementById("svgView");
	tmpcanvas.width = $(svg).attr("width")*realScale;
	tmpcanvas.height = $(svg).attr("height")*realScale;
	currFace.hideProductImg(true);
	if(currFace.bg && currFace.bg.repeat){
		currFace.showBgOnly(true);//隐藏除了重复背景的所有元素，以生成背景
		//图片方式生成背景
		createByImg(tmpcanvas, realScale, function(){
			currFace.showBgOnly(false);
			currFace.showFgOnly(true);
			createByCanvg(tmpcanvas, realScale, toCropImage);
		});
	}else{
		createByCanvg(tmpcanvas, realScale, toCropImage);
	}
	
	//裁剪图片
	function toCropImage(){
		currFace.hideProductImg(false);
		var b = Design.mainEditer.getEditeRect();
		var newimg = new Image();
		newimg.onload = function(){
			var cx = (b.x + bb.x)*realScale;
			var cy = (b.y + bb.y)*realScale;
			var newcanvas = document.createElement("canvas");
			newcanvas.width = realScale * b.width;
			newcanvas.height = realScale * b.height;
			var newctx = newcanvas.getContext("2d");
			newctx.drawImage(newimg, cx, cy, newcanvas.width, newcanvas.height, 0, 0, newcanvas.width, newcanvas.height);
			var thumbnail = newcanvas.toDataURL();
			thumbnail = thumbnail.replace(/^data:image\/(png|jpg);base64,/, "");
			
			callBack(thumbnail);
		};
		newimg.src = tmpcanvas.toDataURL();
	}
}

var currFaceId = null;
var loadingid = null;

exports.doSave = function() {
	if(_issaveing) return;
	_issaveing = true;
	loadingid = layer.load();
	currFaceId = Design.mainEditer.currFace().id;
	Design.tool.setTarget(null);

	_zip = new JSZip();
	var jsondata = Design.mainEditer.getSaveData();
	_zip.file("design.json", JSON.stringify(jsondata));

	var index = 0;
	var keys = Design.mainEditer.product.faces.keys();
	nextFace();

	function nextFace() {
		saveFace(keys[index], faceEnd);

		function faceEnd() {
			index++;
			if (index < keys.length) {
				saveFace(keys[index], faceEnd);
			} else {
				allFaceEnd();
			}
		}
	}

	function allFaceEnd() {
		toinit();
		_zip.generateAsync({
				type: "blob"
			})
			.then(function(content) {
				if (config_gl.apiPath.indexOf("http://127.0.0.1") != -1 || true) {
					//保存到本地
					saveAs(content, "design.zip");
				}

				upload(content);
			});
	}
	
	function toinit(){
		Design.mainEditer.product.activeFace(currFaceId);
		var currFace = Design.mainEditer.product.currFace;
		currFace.showBgOnly(false);
		currFace.showFgOnly(false);
		currFace.hideProductImg(false);
		
		var svg = document.getElementById("svgView");
		$(svg).attr("width", Design.stageW);
		$(svg).attr("height", Design.stageH);
	}
}

var _tmpthumbnail = null;
var _tmpproduction = null;
var _needFillFaceArr = [];

function saveFace(id, callBack) {
	var face = Design.mainEditer.product.activeFace(id);
	var faceName = face.name;
	createThumbnail(function(thumbnail) {
		createProduction(function(production) {
			_tmpthumbnail = thumbnail;
			_tmpproduction = production;
			//缩略图
			_zip.file(faceName + "/thumbnail.png", thumbnail, {
				base64: true
			});
			//生产图
			_zip.file(faceName + "/production.png", production, {
				base64: true
			});
			
			callBack();
		});
	});
}

function upload(content) {
	//http://47.106.65.176:9000/api/upload/file
	var url = config_gl.apiPath + "upload/file";

	var formData = new FormData();
	formData.append('file', content);

	$.ajax({
		type: "POST",
		url: url,
		crossDomain: true,
		data: formData,
		contentType: false,
		processData: false,
		error: function(data) {
			layer.alert("上传zip文件失败");
		},
		success: function(data) {
			if(loadingid){
				layer.close(loadingid);
				loadingid = null;
				_issaveing = false;
			}
		}
	});
}

module.exports = exports;
